package com.comment.util.pay;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 权重抽奖
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class WeightDraw {
    private List<Prize> pool;
    private Long totalWeight;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static final class Prize {
        private Long id;
        private Long weight;
    }


    public WeightDraw(List<Prize> pool) {
        this.pool = pool;
        this.totalWeight = pool.stream().mapToLong(Prize::getWeight).sum();
    }

    public Prize drawCard() {
        // 随机
        long randomValue = ThreadLocalRandom.current().nextLong(0L, totalWeight + 1);

        long currentPrizeWeight = 0;
        for (Prize prize : pool) {
            currentPrizeWeight += prize.getWeight();
            if (randomValue <= currentPrizeWeight) {
                return prize;
            }
        }
        return null;
    }
}
